package com.ctl.jvm;

import com.ctl.juc.ThreadPoolExecutors;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: ThreadSafeEvictingQueue</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2019</p>
 * <p>Company: www.ctl.com</p>
 * 安全的有容量限制的先进先出队列
 * @author ctl
 * @version 1.1
 * @date 2024-07-04 09:55
 */
@BenchmarkMode(Mode.Throughput)
class ThreadSafeEvictingQueue<E> extends LinkedBlockingQueue<E> {
    private final int maxSize;

    public ThreadSafeEvictingQueue(int maxSize) {
        super(maxSize);
        this.maxSize = maxSize;
    }

    @Override
    public synchronized boolean offer(E e) {
        if (size() >= maxSize) {
            poll(); // 移除队首元素
        }
        return super.offer(e);
    }

    @Override
    public synchronized boolean add(E e) {
        if (size() >= maxSize) {
            poll(); // 移除队首元素
        }
        return super.add(e);
    }
}


public class ThreadSafeEvictingQueueTest {

    public static void main(String[] args) {
        ThreadSafeEvictingQueue<Integer> queue = new ThreadSafeEvictingQueue<>(5);

        for (int i = 0; i < 20; i++) {
            int sleepTime = new Random().nextInt(100);
            int finalI = i;
            if (sleepTime % 2 == 0) {
                ThreadPoolExecutors.threadPoolExecutor.execute(() -> {
                    try {
                        TimeUnit.MILLISECONDS.sleep(sleepTime);
                    } catch (Exception e) {
                    }
                    queue.add(finalI);
                    System.out.println("Queue content: " + queue);
                });
            } else {
                ThreadPoolExecutors.threadPoolExecutor1.execute(() -> {
                    try {
                        TimeUnit.MILLISECONDS.sleep(sleepTime);
                    } catch (Exception e) {
                    }
                    queue.add(finalI);
                    System.out.println("Queue content: " + queue);
                });
            }
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (Exception e) {

        }
        ThreadPoolExecutors.threadPoolExecutor.shutdown();
        ThreadPoolExecutors.threadPoolExecutor1.shutdown();
        ThreadPoolExecutors.threadPoolExecutor.shutdownNow();
        ThreadPoolExecutors.threadPoolExecutor1.shutdownNow();
    }
}
